package com.tanhua.dubbo.api;

import com.tanhua.mongo.Friend;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class FriendApiImpl implements FriendApi{
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 添加好友关系
     * @param userId
     * @param friendId
     */
    @Override
    public void contacts(Long userId, Long friendId) {
        //判断是否有好友关系存在
        Query query1 = Query.query(Criteria.where("userId").is(userId)
                                    .and("friendId").is(friendId));
        if(mongoTemplate.exists(query1,Friend.class)){
            //保存好友关系
            Friend friend1 = new Friend();
            friend1.setUserId(userId);
            friend1.setFriendId(friendId);
            friend1.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend1);
        }
        //判断是否反过来有好友关系存在
        Query query2 = Query.query(Criteria.where("userId").is(friendId)
                .and("friendId").is(userId));
        if(mongoTemplate.exists(query2,Friend.class)){
            //保存好友关系
            Friend friend1 = new Friend();
            friend1.setUserId(friendId);
            friend1.setFriendId(userId);
            friend1.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend1);
        }
    }

    /**
     * 获取联系人列表
     * @param userId
     * @param page
     * @param pagesize
     * @return
     */
    @Override
    public List<Friend> getContactsList(Long userId, Integer page, Integer pagesize) {
        Query query = Query.query(Criteria.where("userId").is(userId))
                                    .skip((page - 1 ) * pagesize)
                                    .limit(pagesize)
                                    .with(Sort.by(Sort.Order.desc("created")));
        return mongoTemplate.find(query,Friend.class);
    }
}
